//
//  CZComposePictureView.swift
//  WeiBo
//
//  Created by Apple on 16/9/8.
//  Copyright © 2016年 KY. All rights reserved.
//

import UIKit

//  cell的重用标记
private let CZComposePictureViewCellIdentifier = "CZComposePictureViewCellIdentifier"

//  撰写自定义配图
class CZComposePictureView: UICollectionView {

    //  执行添加图片的闭包
    var addImageClosure: (()->())?
    
    //  图片数据源
    lazy var images: [UIImage] = [UIImage]()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  设置控件
    private func setupUI() {
        //  默认配图隐藏
        isHidden = true
        //  注册cell
        register(CZComposePictureViewCell.self, forCellWithReuseIdentifier: CZComposePictureViewCellIdentifier)
        //  设置数据源代理
        dataSource = self
        delegate = self
    }
    
    //  添加图片
    func addImage(image: UIImage) {

        //  大于等于9张图片隐藏
        if images.count >= 9 {
            return
        }
        //  添加图片显示
        isHidden = false
        images.append(image)
        reloadData()
        
    }
    
    
    //  在layout里面确定每项的大小
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //  每项之间的间距
        let itemMargin: CGFloat = 5
        //  每项的宽度
        let itemWidth = (width - 2 * itemMargin) / 3
        
        //  获取布局对象
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
    }
    
    
   
}

// MARK: -- UICollectionViewDataSource
extension CZComposePictureView: UICollectionViewDataSource, UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        if images.count == 0 || images.count == 9 {
            return images.count
        } else {
            return images.count + 1
        }
        
    }
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CZComposePictureViewCellIdentifier, for: indexPath) as! CZComposePictureViewCell
        
        //  判断索引小于数组个数，取值
        if indexPath.item < images.count {
            cell.image = images[indexPath.item]
            
            //  删除图片闭包
            cell.deleteButtonClosure = { [weak self] in
                //  删除图片
                self?.images.remove(at: indexPath.item)
                if self?.images.count == 0 {
                    self?.isHidden = true
                } else {
                    //  重新加载数据
                    self?.reloadData()
                }
                
            }
            
        } else {
            //  设置加号
            cell.image = nil
            
        }
        
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //  最后一个cell是加号按钮
        if indexPath.item == images.count {
            collectionView.deselectItem(at: indexPath, animated: true)
            //  执行打开图片浏览器的操作
            addImageClosure?()
        }
    }
    
}

//  自定义配图cell
class CZComposePictureViewCell: UICollectionViewCell {
    
    //  删除按钮的点击
    var deleteButtonClosure: (()->())?
    
    // MARK:    --懒加载控件
    private lazy var imageView: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
    //  删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        button.addTarget(self, action: #selector(deleteButtonAction), for: .touchUpInside)
        button.setImage(UIImage(named: "compose_photo_close"), for: .normal)
        return button
    }()
    //  显示的图片
    var image: UIImage? {
        didSet {
            if image == nil {
                imageView.image = UIImage(named: "compose_pic_add")
                imageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.isHidden = true
            } else {
                imageView.image = image
                imageView.highlightedImage = nil
                deleteButton.isHidden = false
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(deleteButton)
        imageView.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView).offset(UIEdgeInsets.zero)
        }
        deleteButton.snp_makeConstraints { (make) in
            make.trailing.equalTo(imageView)
            make.top.equalTo(imageView)
        }
    }
    
    // MARK: -- 删除按钮点击
    @objc private func deleteButtonAction() {
        //  删除图片
        deleteButtonClosure?()
    }
    
    
}









